package com.yanhao.http

import android.content.Context
import android.util.Log
import com.yanhao.utils.MMKVUtils
import okhttp3.*
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import java.util.logging.Level


object RetrofitFactory {

    val BASEURL = "https://www.wanandroid.com/"
    var mapCookie = mutableMapOf<HttpUrl, MutableList<Cookie>>()
    private val okHttpClientBuilder: OkHttpClient.Builder
        get() {
            return OkHttpClient.Builder()
                .callTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .addInterceptor { chain ->
                    val originalResponse = chain.proceed(chain.request())
                    //这里获取请求返回的cookie
                    if (!originalResponse.headers("Set-Cookie").isEmpty()) {
                        val cookies: HashSet<String> = HashSet()
                        for (header in originalResponse.headers("Set-Cookie")) {
                            cookies.add(header)
                        }
                        MMKVUtils.saveCook(cookies)
                        Log.e("TAG", "intercept: ${cookies}")
                    }
                    originalResponse
                }
                .addInterceptor(object : Interceptor {
                    override fun intercept(chain: Interceptor.Chain): Response {
                        val builder = chain.request().newBuilder()
                        val cookies = MMKVUtils.getCook()
                        if (cookies != null) {
                            for (cookie in cookies) {
                                builder.addHeader("Cookie", cookie)
                            }
                        }
                        return chain.proceed(builder.build())
                    }
                })
                .addInterceptor(getLogInterceptor())

        }


    fun factory(): Retrofit {
        val okHttpClient = okHttpClientBuilder.build()
        return Retrofit.Builder()
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(BASEURL)
            .build()
    }

    /**
     * 日志拦截器
     */
    private fun getLogInterceptor(): Interceptor {
        return HttpLoggingInterceptor("Okhttp").apply {
            setPrintLevel(HttpLoggingInterceptor.Level.BODY)
            setColorLevel(Level.INFO)
        }
    }

}